const minute_label=document.querySelector('span.minute')
const second_label=document.querySelector('span.second')
const time_panel=document.querySelector('.time-panel')

let minute=0
let second=0
let running=true
let timer=null

function get_time_countdown() {
    return fetch('/seconds')
    .then(res=>{
        // if (res.status!=200) {
        //     if(!debug)  alert('失去对服务器的访问！')
        //     running=false
        //     return
        // }
        return res.text()
    })
    .then(text=>{
        let seconds=parseInt(text)
        log('get seconds:',seconds)
        if (seconds<0) {
            running=false
            return
        }
        minute=Math.floor(seconds/60)
        second=seconds % 60
        log(minute,second)
    })
    .catch(e=>{
        control_cb.checked=false
        pause_count_down()
        alert('失去对服务器的访问！')
    })

}

function set_time_label() {
    let minute_str=minute>9 ? minute.toString() :`0${minute}`
    let second_str=second>9 ? second.toString() :`0${second}`
    minute_label.textContent=minute_str
    second_label.textContent=second_str
}

function stop_timer(){
    if (timer) {
        clearInterval(timer)
        timer=null
    }
}



async function start_countdown() {
    stop_timer()
    if (!running) {
        return
    }
    await get_time_countdown()
    timer=setInterval(() => {
        if (!running) {
            stop_timer()
            return
        }
        second-=1
        if (second<0){
            minute-=1
            second=59
        }
        if (minute<0) {
            stop_timer()
            start_countdown()
            return           
        }
        set_time_label(minute,second)
    }, 1000);
    return timer
}

function pause_count_down() {
    running=false
    time_panel.classList.add('paused')
    minute=0
    second=0
    set_time_label()
}

function resume_count_down() {
    running=true
    time_panel.classList.remove('paused')
    start_countdown()
}

start_countdown()

